class DenoisingAutoencoder(models.Model):
    def __init__(self):
        super(DenoisingAutoencoder, self).__init__()
        self.encoder = models.Sequential([
            layers.InputLayer(input_shape=(28, 28, 1)),
            layers.Conv2D(32, 3, activation='relu', strides=2, padding='same'),
            layers.Conv2D(64, 3, activation='relu', strides=2, padding='same'),
            layers.Flatten(),
            layers.Dense(128, activation='relu')
        ])
        self.decoder = models.Sequential([
            layers.InputLayer(input_shape=(128,)),
            layers.Dense(7 * 7 * 64, activation='relu'),
            layers.Reshape((7, 7, 64)),
            layers.Conv2DTranspose(32, 3, activation='relu', strides=2, padding='same'),
            layers.Conv2DTranspose(1, 3, activation='sigmoid', strides=2, padding='same')
        ])

    def call(self, x):
        encoded = self.encoder(x)
        decoded = self.decoder(encoded)
        return decoded

# 添加噪声
def add_noise(x, noise_factor=0.5):
    return x + noise_factor * tf.random.normal(tf.shape(x))

# 训练去噪自编码器
dae = DenoisingAutoencoder()
dae.compile(optimizer='adam', loss='binary_crossentropy')
noisy_x_train = add_noise(x_train)
dae.fit(noisy_x_train, x_train, epochs=30, batch_size=128)